﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using IM.Interfaces;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using IM.Interfaces.Protocols;

namespace IM.Protocols.XMPP
{
    public partial class Settings : UserControl, IProtocolSettings
    {

        public Settings()
        {
            InitializeComponent();
            this.Load += new EventHandler(Settings_Load);
        }

        void Settings_Load(object sender, EventArgs e)
        {
            this.txtLogin.Focus();
        }

        public new bool Validate()
        {
            bool suceed = !String.IsNullOrEmpty(txtLogin.Text);
            suceed &= !String.IsNullOrEmpty(txtPassword.Text);
            suceed &= !String.IsNullOrEmpty(txtPort.Text);

            return suceed;
        }

        public void SetSettingsData(Object data)
        {
            SettingsData setData = data as SettingsData;

            if (data == null)
                throw new NullReferenceException("Incoming SettingsData are invalid.");

            this.txtLogin.Text = setData.Login;
            this.txtPassword.Text = setData.Password;
            this.txtPort.Text = setData.Port.ToString();
            this.Enabled = setData.Enabled;
        }

        public Object GetSettingsData(Object protocolCurrentSettings)
        {
			//TODO Validation
            SettingsData settings = protocolCurrentSettings as SettingsData;
            settings.Login = this.txtLogin.Text;
            settings.Password = this.txtPassword.Text;
            settings.Enabled = this.chckIsEnabled.Checked;
			
			if (!string.IsNullOrEmpty(this.txtPort.Text))
			{
				var port = - 1;
				if (!int.TryParse(this.txtPort.Text, out port))
					throw new FormatException("Port number must be integer!");
				settings.Port = port;
			}
			else
			    throw new NullReferenceException("Port number must be specified!");

            return settings as Object;
        }

        public Type GetSettingsDataType()
        {
            return typeof(SettingsData);
        }

        public Control GetSettingsControl()
        {
            return this;
        }
    }
}
